<script setup>
import {  useRoute } from "vue-router";
import { io } from "socket.io-client";
import { ref } from "vue";
const userlists=ref([])
const obj=ref({
  message:{
    users:[],
    values:[]
  },
  userId:''
})
const user=ref(null)
const content=ref('')
const route=useRoute()
const 接收的消息=ref({})
const sort = (list, id) => {
  list.sort((a, b) => {
    if (a.id === id) {
      return -1; // 将 id 为 socket.id 的对象排在前面
    } else if (b.id === id) {
      return 1; // 将 id 为 "zs" 的对象排在前面
    } else {
      return 0; // 保持原始顺序
    }
  });
}
const socket = io("http://localhost:3000", {
    query:{username:route.query.username}
});
socket.on("login",({id,userlist})=>{
  id&& (user.value={username:route.query.username,id})
  sort(userlist,user.value.id)
  userlists.value=userlist
})
socket.on("xt",()=>{
 user.value&& socket.emit("xtEnd",user.value)
  
})
socket.on('SendMessage',(data)=>{
    console.log(data,'接收到的消息');
    接收的消息.value[data.users[0]===user.value.id?data.users[1]:data.users[0]]=data 
})
const send =()=>{
  obj.value.message.users=[user.value.id,obj.value.userId]
  obj.value.message.values=[{content:content.value,date:new Date().getTime(),id:user.value.id}]
  socket.emit('SendMessage',obj.value.message)
}
</script>

<template>
  
<div>
<ul>

    <li :class="{active:item.id===obj.userId}" @click="item.id!=user.id&&(obj.userId=item.id)" v-for="item in userlists">{{ item.username }}({{ 接收的消息[item.id]?.values.length||"0" }})</li>
</ul>

<button @click="send">发送</button>
<input type="text" v-model="content">
<template v-for="item in userlists">
  <ul  v-show="item.id===obj.userId||(item.id===user.id&&obj.userId===接收的消息[item.id]?.users[1])" >
    <li v-for="ele in 接收的消息[item.id]?.values"><span>{{ userlists.filter(ite=>ite.id===ele.id)[0].username }}</span> ::<span>{{ ele.content }}</span></li>
  </ul>

</template>
</div>
</template>

<style scoped>
.active{
  color:brown;
}
</style>
